package utilities;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

/**
 * Basic utilities for handling documents
 * 
 * @author fparks
 * 
 */
public final class DocumentUtilities {
	private static final Logger LOG = LoggerFactory
			.getLogger(DocumentUtilities.class);

	private DocumentUtilities() {
	}

	/**
	 * Given the name of an output file, this will attempt to create an output
	 * file with that name if one doesn't already exist. If will return true or
	 * false for file created.
	 * 
	 * @param output
	 * @return
	 */

	public static boolean doesThisFileExist(String fileName) {
		boolean exists = true;
		if (exists) {
			exists = new File(fileName).isFile();
		} else {
			exists = false;
		}
		return exists;

	}
/**
 * 
 * @param output file name
 * @return the created file
 */
	public static boolean createOutputFile(String output) {
		boolean fileCreated = false;

		File f = new File(output);
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				LOG.error("***File not created - IO Exception***");
			}
			System.out.println("New file " + output + " has been created. ");
			fileCreated = true;
		} else {
			System.out.println(" The file was not created. ");
		}

		return fileCreated;
	}

	/**
	 * 
	 * @param usersMainFile
	 *            Given the filename, this will build and return the main
	 *            document to be modified
	 * @return the built document
	 */
	public static Document buildDoc(String usersMainFile) {
		Document doc = null;

		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			File mainFile = new File(usersMainFile);
			doc = dBuilder.parse(mainFile);
			doc.getDocumentElement().normalize();
		} catch (Exception e) {
			LOG.error("** A valid file with name "+ usersMainFile + " could not be found**");
		}
		
		return doc;
		
	}

	/**
	 * 
	 * @param usersFilelet
	 *            Given the filename of the file to be inserted, this will build
	 *            and return the document
	 * @return the built document
	 */
	public static Document buildDoclet(String usersFilelet) {
		Document doclet = null;
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

			// xml piece to be inserted
			File piece = new File(usersFilelet);
			doclet = dBuilder.parse(piece);
			doclet.getDocumentElement().normalize();
		} catch (Exception e) {
			LOG.error(" A valid file with name " + usersFilelet + " could not be found" );
		}
		return doclet;
	}
}
